import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import {
  Badge,
  Button,
  Card,
  Col,
  Divider,
  Form,
  Input,
  InputNumber,
  Radio,
  message,
  Modal,
  Row,
  Select,
  Table,
  List,
  Checkbox,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import TagSelect from '@/components/TagSelect';
import DescriptionList from '@/components/DescriptionList';
import FooterToolbar from '@/components/FooterToolbar';
import Dict from '@/components/Dict';

const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const {Description} = DescriptionList;

const typeMap = {
  tinyint: 'Integer',
  smallint: 'Integer',
  mediumint: 'Integer',
  int: 'Integer',
  integer: 'Integer',
  bigint: 'Long',
  float: 'Float',
  double: 'Double',
  decimal: 'BigDecimal',
  char: 'String',
  varchar: 'String',
  tinytext: 'String',
  text: 'String',
  mediumtext: 'String',
  longtext: 'String',
  date: 'Date',
  datetime: 'Date',
  timestamp: 'Date'
};

const formItemLayout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 14,
  },
};


@connect(({generate, loading}) => ({
  generate,
  loading: loading.models.generate,
}))
@Form.create()
export default class Generate extends PureComponent {
  state = {
    modalVisible: false,
    itemType: 'create',
    item: {},
    queryListObj: {},
  };

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'generate/getTableList',
    });
  }

  /**
   * 查询表字段
   */
  queryTableColumnList = (tableName) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'generate/getTableColumnList',
      payload: {
        tableName
      },
      callback: () => {
        let queryListObj = {};
        this.props.generate.tableColumnList.map(item => {
          queryListObj[item.columnName] = item;
        });
        this.setState({queryListObj: queryListObj})
      }
    });
  }

  generate = () => {
    const {dispatch, form} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return;
      }
      let data = fieldsValue;
      data.queryList = [];
      data.tableList = [];
      data.formList = [];
      data.detailList = [];
      Object.keys(data.columnComment).map(key => {
        let obj = {
          columnName: key,
          columnJavaName: this.getJavaFieldName(key),
          columnComment: data.columnComment[key],
          dataType: data.dataType[key],
          dict: data.dict[key] || '',
          sort: data.sort[key],
        };
        if (data.opt[key].filter(item => item === 'query').length > 0) {
          data.queryList.push(obj);
        }
        if (data.opt[key].filter(item => item === 'table').length > 0) {
          data.tableList.push(obj);
        }
        if (data.opt[key].filter(item => item === 'form').length > 0) {
          data.formList.push(obj);
        }
        if (data.opt[key].filter(item => item === 'detail').length > 0) {
          data.detailList.push(obj);
        }
      });
      data.queryList.sort((a, b) => a.sort - b.sort);
      data.tableList.sort((a, b) => a.sort - b.sort);
      data.formList.sort((a, b) => a.sort - b.sort);
      data.detailList.sort((a, b) => a.sort - b.sort);
      data.tableJavaName = this.getJavaFieldName(data.tableName);
      delete data.columnName;
      delete data.columnComment;
      delete data.dataType;
      delete data.opt;
      delete data.dict;
      dispatch({
        type: 'generate/gen',
        payload: data,
      });
    });

  }

  getJavaFieldName = (str) => {
    let strArr = [];
    str.split('_').map((item, index) => {
      if (index > 0) {
        item = item.substring(0, 1).toUpperCase() + item.substring(1, item.length);
      }
      strArr.push(item)
    });
    return strArr.join('')
  }

  getTableColumnList = data => {
    return data.filter(item => item.columnName !== 'id' && item.columnName !== 'del_flag'
      && item.columnName !== 'create_date' && item.columnName !== 'create_user_id'
      && item.columnName !== 'update_date' && item.columnName !== 'update_user_id'
      && item.columnName !== 'parent_id').map(item => {
      if (typeMap[item.dataType])
        item.dataType = typeMap[item.dataType];
      return item;
    });
  };


  render() {
    const {generate: {tableList, tableColumnList}, loading, form} = this.props;
    const {queryListObj,} = this.state;

    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <Form>
            <Divider orientation="left">基本信息</Divider>
            <Row>
              <Col span={8}>
                <FormItem label="表名：" hasFeedback {...formItemLayout}>
                  {form.getFieldDecorator('tableName', {
                    rules: [
                      {
                        required: true,
                        message: '请选择数据表',
                      },
                    ],
                  })(
                    <Select
                      showSearch
                      style={{width: 200}}
                      placeholder="请选择数据表"
                      optionFilterProp="children"
                      onSelect={value => this.queryTableColumnList(value)}
                      filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    >
                      {tableList && tableList.map(item => {
                        return <Option value={item.tableName}
                                       key={item.tableName}>{item.tableName}({item.tableComment})</Option>
                      })}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label="模块名：" hasFeedback {...formItemLayout}>
                  {form.getFieldDecorator('moduleName', {
                    rules: [
                      {
                        required: true,
                        message: '请输入模块名',
                      },
                    ],
                  })(<Input/>)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label="作者：" hasFeedback {...formItemLayout}>
                  {form.getFieldDecorator('author', {
                    rules: [
                      {
                        required: true,
                        message: '请输入作者',
                      },
                    ],
                  })(<Input/>)}
                </FormItem>
              </Col>

              <Divider orientation="left">菜单信息（如果菜单名称为空，则不会生成菜单）</Divider>
              <Col span={8}>
                <FormItem label="菜单名：" hasFeedback {...formItemLayout}>
                  {form.getFieldDecorator('menuName')(<Input/>)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label="菜单多语KEY：" hasFeedback {...formItemLayout}>
                  {form.getFieldDecorator('menuLocalesKey')(<Input/>)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label="菜单图标：" hasFeedback {...formItemLayout}>
                  {form.getFieldDecorator('menuIcon')(<Input/>)}
                </FormItem>
              </Col>

              <Divider orientation="left">布局</Divider>
              <Col span={8}>
                <FormItem label="布局：" hasFeedback {...formItemLayout}>
                  {form.getFieldDecorator('layout', {
                    initialValue: 'baseTable',
                  })(
                    <RadioGroup>
                      <Radio value={'baseTable'}>基本表格布局</Radio>
                      <Radio value={'treeTable'}>树表格布局</Radio>
                      <Radio value={'leftTreeTable'}>左树右表格布局</Radio>
                    </RadioGroup>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label="生成项：" hasFeedback {...formItemLayout}>
                  {form.getFieldDecorator('genItem', {
                    initialValue: ['query', 'table', 'form', 'detail'],
                  })(
                    <Checkbox.Group>
                      <Checkbox value={'query'}>查询</Checkbox>
                      <Checkbox value={'table'}>列表</Checkbox>
                      <Checkbox value={'form'}>表单</Checkbox>
                      <Checkbox value={'detail'}>详情</Checkbox>
                    </Checkbox.Group>
                  )}
                </FormItem>
              </Col>

              <Divider orientation="left">字段信息</Divider>
              <Col span={24}>
                <List
                  bordered
                  size="small"
                  dataSource={this.getTableColumnList(tableColumnList)}
                  renderItem={(item, index) => (<List.Item>
                  <span style={{width: '150px', textAlign: 'right'}}>
                    {item.columnName}：
                  </span>
                    {form.getFieldDecorator(`columnComment[${item.columnName}]`, {initialValue: item.columnComment})(
                      <Input style={{width: '100px'}}/>
                    )}
                    <span style={{width: '20px'}}/>
                    {form.getFieldDecorator(`dataType[${item.columnName}]`, {initialValue: item.dataType})(
                      <Select style={{width: 100}}>
                        <Option value="Integer">Integer</Option>
                        <Option value="Long">Long</Option>
                        <Option value="Float">Float</Option>
                        <Option value="Double">Double</Option>
                        <Option value="BigDecimal">BigDecimal</Option>
                        <Option value="String">String</Option>
                        <Option value="Date">Date</Option>
                      </Select>
                    )}
                    <span style={{width: '20px'}}/>
                    {form.getFieldDecorator(`dict[${item.columnName}]`)(
                      <Input style={{width: '100px'}}/>
                    )}
                    <span style={{width: '20px'}}/>
                    {form.getFieldDecorator(`sort[${item.columnName}]`)(
                      <InputNumber style={{width: '80px'}}/>
                    )}
                    <span style={{width: '20px'}}/>
                    {form.getFieldDecorator(`opt[${item.columnName}]`, {initialValue: ['form', 'detail']})(
                      <Checkbox.Group>
                        <Checkbox value={'query'}>查询</Checkbox>
                        <Checkbox value={'table'}>列表</Checkbox>
                        <Checkbox value={'form'}>表单</Checkbox>
                        <Checkbox value={'detail'}>详情</Checkbox>
                      </Checkbox.Group>
                    )}
                  </List.Item>)}
                />
              </Col>
            </Row>
            <br/>
            <br/>
          </Form>
          <FooterToolbar>
            <Button type="primary" onClick={this.generate}>生成</Button>
          </FooterToolbar>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
